<template>
  <el-card>
    <!--  新增/修改弹出框  -->
    <el-dialog :title="dialogTitle + '标签'" :visible.sync="dialogAddOrUpdate" width="40%" :before-close="handleCloseAdd">
      <el-form :model="taskFrom" :rules="taskFromRules" ref="taskFrom" label-width="100px">

        <el-form-item label="任务名称" prop="name">
          <el-input v-model="taskFrom.name"></el-input>
        </el-form-item>

        <el-form-item label="任务Bean" prop="beanName">
          <el-input v-model="taskFrom.beanName" placeholder="(后端类名的小写或通过注解显式指定了名称)"></el-input>
        </el-form-item>

        <el-form-item label="任务方法" prop="methodName">
          <el-input v-model="taskFrom.methodName"></el-input>
        </el-form-item>

        <el-form-item label="方法参数" prop="methodParams">
          <el-input v-model="taskFrom.methodParams"></el-input>
        </el-form-item>

        <el-form-item label="cron表达式" prop="cronExpression">
          <el-popover v-model="cronPopover">
            <cron @change="changeCron" @close="cronPopover = false" i18n="cn"></cron>
            <el-input slot="reference" @click="cronPopover = true" v-model="taskFrom.cronExpression"
              placeholder="请输入定时策略,已自动优化格式"></el-input>
          </el-popover>
        </el-form-item>

        <el-form-item label="任务描述" prop="taskExplain">
          <el-input v-model="taskFrom.taskExplain"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="taskFrom.status">
            <el-radio :label=0>静默</el-radio>
            <el-radio :label=1>立即启用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddOrUpdateForm('taskFrom')">立即{{ dialogTitle }}</el-button>
          <el-button @click="resetForm('taskFrom')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  表格操作  -->
    <div class="select-div">

      <el-input clearable v-model="keywords" prefix-icon="el-icon-search" size="small" placeholder="请输入任务名称关键字"
        style="width:200px" @keyup.enter.native="searchTask" />

      <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem" @click="searchTask">
        搜索
      </el-button>

      <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogAdd">新增</el-button>

      <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
        :disabled="this.selection.length === 0">删除选中
      </el-button>

    </div>

    <!--  表格内容  -->
    <el-table :data="tableData" border :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="name" label="任务名称" fixed width="150"></el-table-column>

      <el-table-column prop="beanName" label="对象Bean" width="200"></el-table-column>

      <el-table-column prop="methodName" label="方法名称" width="150"></el-table-column>

      <el-table-column prop="methodParams" label="方法参数" width="150"></el-table-column>

      <el-table-column prop="cronExpression" label="cron表达式" width="150"></el-table-column>

      <el-table-column prop="status" label="状态" sortable width="150">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" active-text="启动"
            inactive-text="停止" :active-value="1" :inactive-value="0" @change="changeStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column prop="taskExplain" label="任务描述" width="150"></el-table-column>

      <el-table-column prop="lastExecutionTime" label="最后执行时间" sortable width="200"></el-table-column>

      <el-table-column prop="executionDuration" label="执行用时(ms)" sortable width="150"></el-table-column>

      <el-table-column prop="createTime" label="创建时间" sortable width="200"></el-table-column>

      <el-table-column prop="updateTime" label="修改时间" sortable width="200"></el-table-column>

      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="编辑" placement="top-start">
            <el-button circle icon="el-icon-edit" size="mini" @click="dialogUpdate(scope.row.id)" />
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" type="danger" @click="deleteCheck(scope.row.id)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <pagination :total="total" :page_index="pageNum" @pageChange="pageChange" />
  </el-card>
</template>

<script>
import { timedTaskApi } from '@/api';
import { cron } from 'vue-cron';
import 'element-ui/lib/theme-chalk/index.css'

export default {
  name: "TimedTask",
  components: { cron },
  data() {
    return {
      tableData: [],
      taskFrom: {},
      total: 0,
      pageNum: 1,
      pageSize: 10,
      keywords: null,
      selection: [],
      selectedNum: 0,
      dialogAddOrUpdate: false,
      dialogTitle: '',
      taskFromRules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        beanName: [
          { required: true, message: '请输入任务类名', trigger: 'blur' }
        ],
        methodName: [
          { required: true, message: '请输入任务方法名', trigger: 'blur' }
        ],
        cronExpression: [
          { required: true, message: '请输入cron表达式', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
      },
      cronPopover: false,
    }
  },


  methods: {
    changeCron(val) {
      this.taskFrom.cronExpression = this.quartzToSpring(val)
    },

    /**
     * 将Quartz格式转换为Spring格式
     * @param quartzCron quartz表达式
     */
    quartzToSpring(quartzCron) {
      const fields = quartzCron.trim().split(/\s+/);

      // 1. 字段数量处理
      if (fields.length === 7) {
        fields.pop(); // 删除年字段
      }

      // 2. 特殊字段转换
      const [sec, min, hour, day, month, week] = fields;

      return [
        sec === '*' ? '0' : sec,    // 秒：*改为0（避免每秒触发）
        min.replace('0/', '*/'),    // 分：0/5 -> */5
        hour,
        day,
        month,
        week === '?' ? '*' : week   // 周：?改为*
      ].join(' ');
    },

    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },

    /**
     * 新增按钮事件
     */
    dialogAdd() {
      this.dialogTitle = "新增";
      this.dialogAddOrUpdate = true;
    },

    /**
     * input搜索触发事件
     */
    searchTask() {
      this.pageNum = 1;
      this.loadTaskList();
    },

    /**
     * 分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadTaskList()
    },

    // 重置弹出框表单内容
    resetForm(formName) {
      if (this.$refs.taskFrom !== undefined) this.$refs.taskFrom.resetFields();
      this.taskFrom = {};
    },

    /**
     * 当用户通过点击关闭图标或遮罩关闭 Dialog 时起效的事件
     */
    handleCloseAdd() {
      //关闭Dialog时清空表单
      this.resetForm();
      this.dialogAddOrUpdate = false;
      this.taskFrom = {};
    },

    /**
     * 编辑按钮触发事件
     * @param id 数据id
     */
    dialogUpdate(id) {
      this.isDisabled = true;
      timedTaskApi.getTimedTaskInfo(id).then((response) => {
        if (response.data.code === 20000) {
          //将当前行角色信息数据回显到弹出表单中，并打开表单
          this.taskFrom = response.data.data;
          this.dialogTitle = "编辑";
          this.dialogAddOrUpdate = true;
        }
      })
    },

    /**
     * 启用/禁用任务
     */
    changeStatus(rows) {
      this.taskFrom = rows
      timedTaskApi.updateTimedTask(this.taskFrom).then((response) => {
        if (response.data.code === 20000) {
          if (rows.status === 0) {
            this.$message.warning("任务已停止！")
          } else {
            this.$message.success("任务启动成功！")
          }
          this.loadTaskList();
        }
      })
    },

    /**
     * 提交新增/修改表单
     * @param formName
     */
    submitAddOrUpdateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = this.taskFrom;
          const apiMethod = this.taskFrom.id ? timedTaskApi.updateTimedTask : timedTaskApi.addTimedTask;

          apiMethod(data).then((response) => {
            if (response.data.code === 20000) {
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success',
                onClose: () => {
                  this.loadTaskList();
                }
              });
              this.dialogAddOrUpdate = false;
              this.resetForm(formName);
              this.taskFrom = {};
            }
          })
        } else {
          this.$message.warning('请完整填写表单!');
          return false;
        }
      })
    },

    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("删除后不可恢复", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        timedTaskApi.deleteTimedTasks(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message.success("用户删除成功！")
          }
          this.loadTaskList();
        });
      })
    },

    loadTaskList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        keywords: this.keywords,
      };

      timedTaskApi.getTimedTaskList(params).then((response) => {
        if (response.data.code === 20000) {
          this.tableData = response.data.data.pagingList;
          this.total = response.data.data.count;
          return;
        }
        this.tableData = null;
        this.total = null;
      })
    }

  },


  created() {
    this.loadTaskList();
  }

}
</script>

<style scoped></style>